package com.zyf.wjy.service;

import com.zyf.wjy.dao.MaterialDao;
import com.zyf.wjy.entity.Material;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 农资服务类
 */
@Service
public class MaterialService {
    
    @Autowired
    private MaterialDao materialDao;
    
    /**
     * 查询所有农资
     */
    public List<Material> findAll() {
        return materialDao.findAll();
    }
    
    /**
     * 根据ID查询
     */
    public Material findById(Long id) {
        return materialDao.findById(id);
    }
    
    /**
     * 根据类型查询
     */
    public List<Material> findByType(String materialType) {
        return materialDao.findByType(materialType);
    }
    
    /**
     * 批量保存农资
     */
    public List<Material> saveAll(List<Material> materials) {
        return materials.stream()
            .map(this::save)
            .toList();
    }
    
    /**
     * 保存农资
     */
    public Material save(Material material) {
        if (material.getId() == null) {
            material.setCreateTime(LocalDateTime.now());
        }
        return materialDao.save(material);
    }
    
    /**
     * 删除农资
     */
    public boolean deleteById(Long id) {
        return materialDao.deleteById(id);
    }
    
    /**
     * 批量删除
     */
    public boolean deleteByIds(List<Long> ids) {
        return materialDao.deleteByIds(ids);
    }
    
    /**
     * 更新库存（入库）
     */
    public void stockIn(Long materialId, Double quantity) {
        Material material = materialDao.findById(materialId);
        if (material != null) {
            material.setQuantity(material.getQuantity() + quantity);
            materialDao.save(material);
        }
    }
    
    /**
     * 更新库存（出库）
     */
    public boolean stockOut(Long materialId, Double quantity) {
        Material material = materialDao.findById(materialId);
        if (material != null) {
            if (material.getQuantity() >= quantity) {
                material.setQuantity(material.getQuantity() - quantity);
                materialDao.save(material);
                return true;
            }
        }
        return false;
    }
}

